package com.padgett.resourcemanagement.invoice;

import java.io.IOException;
import java.util.Date;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.padgett.resourcemanagement.data.ClientDAO;

/**
 * Get Invoice
 * 
 * @author andyleung
 * 
 */
@SuppressWarnings("serial")
public class SaveInvoiceServlet extends HttpServlet{
	@SuppressWarnings("unused")
	private static final Logger logger=Logger.getLogger(SaveInvoiceServlet.class.getName());
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException, ServletException {
		String clientId=req.getParameter("clientId");
		String clientName=req.getParameter("clientName");
		Key clientKey=KeyFactory.stringToKey(clientId);
		Key invoiceKey=new KeyFactory.Builder(clientKey)
		.getKey();
		UserService userService=UserServiceFactory.getUserService();
		User user=userService.getCurrentUser();
		Entity invoice=new Entity("Invoice",invoiceKey);
		invoice.setProperty("InvoiceNumber", new Long(-1));
		invoice.setProperty("IssuedDate", new Date(System.currentTimeMillis()));
		invoice.setProperty("Accountant", user.getEmail());
		invoice.setProperty("Client", clientKey);
		invoice.setUnindexedProperty("BillTo", clientName);
		invoice.setProperty("FullyPaid", Boolean.FALSE);
		invoice.setProperty("CreatedBy", user.getNickname());
		invoice.setProperty("CreatedDate", new Date(System.currentTimeMillis()));
		invoice.setProperty("LastModifiedBy", user.getNickname());
		invoice.setProperty("LastModifiedDate", new Date(System.currentTimeMillis()));
		Key key=ClientDAO.saveInvoice(invoice);
		resp.sendRedirect("/GetInvoice?invoiceId="+KeyFactory.keyToString(key)+"&clientId="+clientId+"&clientName="+clientName);
	}
}
